package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"sort"
	"strconv"

	"github.com/therecipe/qt/gui"

	"github.com/therecipe/qt/core"

	"github.com/therecipe/qt/widgets"
)

type AppGui struct {
	out        *widgets.QTextEdit
	app        *widgets.QApplication
	window     *widgets.QMainWindow
	recFile    *widgets.QLineEdit
	actionFile *widgets.QComboBox
	count      *widgets.QLineEdit
	rec, play  *widgets.QPushButton
	ctx        context.Context
}

type IGui interface {
	Println(some string)
	Printf(f string, args ...interface{})
	OnEnd()
	Context() context.Context
	MakeRecordPath(fn string) string
}

func NewAppGui() *AppGui {
	application := widgets.NewQApplication(len(os.Args), os.Args)
	return &AppGui{out: widgets.NewQTextEdit(nil), app: application, count: widgets.NewQLineEdit(nil)}
}

func (s *AppGui) Show() {
	ctx, cancel := context.WithCancel(context.Background())
	s.ctx = ctx

	w := widgets.NewQMainWindow(nil, core.Qt__Widget)

	s.window = w

	box := widgets.NewQVBoxLayout()

	s.out.SetReadOnly(true)
	s.out.SetFixedSize2(480, 320)

	gr1 := s.createRecordFileGroup()
	box.AddLayout(gr1, 1)
	s.rec = widgets.NewQPushButton2("记录动作", s.window)
	box.AddWidget(s.rec, 1, 0)
	s.rec.ConnectClicked(func(b bool) {
		s.play.SetDisabled(true)
		s.rec.SetDisabled(true)
		go record(s.recFile.Text(), s)
	})

	gr2 := s.createActionFileGroup()
	s.count.SetText("99999")
	box.AddLayout(gr2, 1)
	cg := s.createCountGroup()
	box.AddLayout(cg, 1)
	s.play = widgets.NewQPushButton2("执行动作", s.window)
	box.AddWidget(s.play, 1, 0)
	s.play.ConnectClicked(func(b bool) {
		s.play.SetDisabled(true)
		s.rec.SetDisabled(true)
		c, err := strconv.Atoi(s.count.Text())
		if err != nil {
			log.Println(err)
		} else {
			go play(s.actionFile.CurrentText(), c, s)
		}

	})
	box.AddWidget(s.out, 1, 0)

	quit := widgets.NewQPushButton2("退出程序", s.window)
	box.AddWidget(quit, 1, 0)
	quit.ConnectClicked(func(b bool) {
		s.app.Quit()
	})
	s.window.ConnectCloseEvent(func(e *gui.QCloseEvent) {
		s.app.Quit()
	})
	win := widgets.NewQWidget(s.window, core.Qt__Widget)
	win.SetLayout(box)
	s.window.SetCentralWidget(win)
	s.app.SetActiveWindow(s.window)
	s.window.ShowDefault()
	s.app.Exec()
	cancel()
}

func (s *AppGui) Println(some string) {
	s.out.Append(some + "\n")
	s.scroll()
}

func (s *AppGui) Printf(f string, args ...interface{}) {
	s.out.Append(fmt.Sprintf(f, args...) + "\n")
	s.scroll()
}

func (s *AppGui) Quit() {
	s.app.Quit()
}

func (s *AppGui) getRecordPath() string {
	exe1, err := os.Executable()
	if err != nil {
		log.Println(err.Error())
		return ""
	}
	res := filepath.Join(filepath.Dir(exe1), "records")
	_, err = os.Stat(res)
	if err != nil {
		os.MkdirAll(res, os.ModePerm)
	}

	return res
}

func (s *AppGui) MakeRecordPath(fn string) string {
	return filepath.Join(s.getRecordPath(), fn)
}

func (s *AppGui) createRecordFileGroup() widgets.QHBoxLayout_ITF {
	s.recFile = widgets.NewQLineEdit(s.window)
	s.recFile.SetText("default")
	res := widgets.NewQHBoxLayout()
	res.AddWidget(widgets.NewQLabel2("保存到文件:", s.window, core.Qt__Widget), 1, 0)
	res.AddWidget(s.recFile, 1, 0)
	return res
}

func (s *AppGui) createActionFileGroup() widgets.QHBoxLayout_ITF {
	fp, err := os.Open(s.getRecordPath())
	if err != nil {
		panic(err)
	}
	defer fp.Close()
	files, err := fp.Readdirnames(0)
	if err != nil {
		panic(err)
	}
	sort.Strings(files)
	s.actionFile = widgets.NewQComboBox(s.window)
	if len(files) == 0 {
		files = append(files, "default")
	}
	s.actionFile.AddItems(files)
	s.actionFile.SetCurrentIndex(0)
	res := widgets.NewQHBoxLayout()
	res.AddWidget(widgets.NewQLabel2("执行该文件:", s.window, core.Qt__Widget), 1, 0)
	res.AddWidget(s.actionFile, 1, 0)
	return res
}

func (s *AppGui) createCountGroup() widgets.QHBoxLayout_ITF {
	res := widgets.NewQHBoxLayout()
	res.AddWidget(widgets.NewQLabel2("循环次数:", s.window, core.Qt__Widget), 1, 0)
	res.AddWidget(s.count, 1, 0)
	return res
}

func (s *AppGui) OnEnd() {
	s.rec.SetEnabled(true)
	s.play.SetEnabled(true)
}

func (s *AppGui) scroll() {

}

func (s *AppGui) Context() context.Context {
	return s.ctx
}
